package com.webserver.core;

import com.webserver.http.HttpServerRequest;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;

public class ClientHandler implements Runnable{
    Socket socket;

    public ClientHandler(Socket socket){
        this.socket = socket;
    }

    public void run(){
        try {
            //解析请求
            HttpServerRequest request = new HttpServerRequest(socket);

            //处理请求
            String path = request.getUri();

            //3发送响应
            File rootDir = new File(ClientHandler.class.getClassLoader()
                    .getResource(".").toURI());

            File staticDir = new File(rootDir,"static");

            File file = new File(staticDir,path);

            //3.1发送状态行
            println("HTTP/1.1 200 OK");
            //3.2发送响应头
            println("Content-Type: text/html");
            println("Content-Length: " + file.length());

            println("");
            //3.3发送响应内容
            FileInputStream fis = new FileInputStream(file);
            byte[] data = new byte[1024*10];
            int len = -1;
            OutputStream os = socket.getOutputStream();
            while ((len = fis.read(data)) != -1){
                os.write(data,0,len);
            }


        } catch (IOException | URISyntaxException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void println(String line) throws IOException {
        OutputStream os = socket.getOutputStream();
        byte[] data = line.getBytes(StandardCharsets.ISO_8859_1);

        os.write(data);
        os.write(13);//13回车
        os.write(10);//10换行
    }

}
